package com.atomscat.lottery.service;

import com.atomscat.lottery.entity.db.LotteryActivityUserEntity;
import com.atomscat.lottery.repository.LotteryActivityUserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class LotteryActivityUserService {
    private final LotteryService lotteryService;
    private final LotteryActivityUserRepository lotteryActivityUserRepository;

    @Transactional
    public void createLotteryActivityUser(Long activityId, Long userId) {
        LotteryActivityUserEntity lotteryActivityUserEntity = new LotteryActivityUserEntity();
        lotteryActivityUserEntity.setActivityId(activityId);
        lotteryActivityUserEntity.setUserId(userId);
        lotteryActivityUserRepository.saveAndFlush(lotteryActivityUserEntity);
        if (lotteryActivityUserEntity.getId() != null) {
            lotteryService.addParticipant(activityId, String.valueOf(userId));
        }
    }

    public LotteryActivityUserEntity getLotteryActivityUser(Long activityId, Long userId) {
        LotteryActivityUserEntity lotteryActivityUserEntity = new LotteryActivityUserEntity();
        lotteryActivityUserEntity.setActivityId(activityId);
        lotteryActivityUserEntity.setUserId(userId);
        return lotteryActivityUserRepository.findOne(Example.of(lotteryActivityUserEntity)).orElse(null);
    }

    public List<LotteryActivityUserEntity> getLotteryActivityUsers() {
        return lotteryActivityUserRepository.findAll();
    }
}
